package com.baiku.sanhos.handler;

import com.baiku.sanhos.response.ResultVO;
import com.baiku.sanhos.utils.JWTEasyUtil;
import org.apache.commons.lang3.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired JWTEasyUtil jwtEasyUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        String requestUrl = request.getRequestURI();
        log.debug("requestUrl",requestUrl);

       if(!(handler instanceof HandlerMethod)){

           //否则放掉静态资源
           return  true;
       }
       String token =request.getHeader("token");
       if(StringUtils.isBlank(token)){
           ResultVO resultVO=new ResultVO(1000,"未登录");
           // 设置响应头为JSON格式
           response.setContentType("application/json;charset=utf-8");
           // 将响应数据转换为JSON字符串
           String jsonResponse = new ObjectMapper().writeValueAsString(resultVO);
           // 将JSON字符串写入响应体
           response.getWriter().print(jsonResponse);
           response.sendRedirect("/login.html");

           return false;

       }

       if(!jwtEasyUtil.validateToken(token)){
           log.debug("进入了",jwtEasyUtil);

           ResultVO result = ResultVO.fail();//未登录
           response.setContentType("application/json;charset=utf-8");
           String jsonResponse = new ObjectMapper().writeValueAsString(result);

           response.getWriter().print(jsonResponse);
           response.sendRedirect("/login.html");

           return false;


       }
        //登录成功
        return true;



}}
